package backend

import (
	"fmt"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"lanmon/internal/backend/middleware"

	"lanmon/internal/config"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

type HttpServer struct {
	router *gin.Engine
}

func setupHttpServer(conf *config.Config) (*HttpServer, error) {
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()

	server := &HttpServer{
		router: router,
	}
	server.init()

	go func() {
		port := fmt.Sprintf(":%d", conf.General.PortBackend)
		log.WithField("port", port).Info("http server start.")
		router.Run(port)
	}()

	return server, nil
}

// router
func (b *HttpServer) init() error {
	b.router.Use(middleware.Cros())

	apiv1 := b.router.Group("api/v1")
	{
		admin := apiv1.Group("admin")
		{
			c := NewAdminController()
			admin.GET("/list", c.ListClients)
			admin.POST("/broadcast/:action", c.BroadcastClients)
			admin.POST("/command/:action/:clientId", c.CommandClients)
		}
	}

	// https://github.com/swaggo/swag/
	b.router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	return nil
}
